<script>
import UserApi from '@/api/user';
import { useUserStore } from '@/stores/user';
import { mapStores } from 'pinia';

export default {
  data() {
    return {
      username: "",
      password: "",
      isShow:false,
      msg:""
    };
  },
  methods: {
    async login(){
      console.log(`用户名：${this.username}`);
      console.log(`密码：${this.password}`);
      let api = new UserApi();
      let data = {username:this.username,password:this.password};
      let result = await api.login(data);
      let info = result.data;
      this.msg = info.msg;
      if (info.code === 200){
        console.log("****************");
        this.userStore.setInfo(info.data.user.session.user);
        this.$router.replace("/");
      } else{
        this.isShow = true;
      }
    },
    onChange(){
      this.isShow = false;
    }
  },
  computed: {
    ...mapStores(useUserStore),
  }
};
</script>

<template>
  <div class="login">
    <h2>用户登录</h2>
    <div>
      <label for="username">用户名</label>
      <input type="text" id = "username" placeholder="请输入用户名" v-model="username" v-on:change="onChange">
    </div>
    <div>
      <label for="password">密码</label>
      <input type="password" id = "password" placeholder="请输入密码" v-model="password" v-on:change="onChange">
    </div>
    <el-button type="primary" plain @click="login">登录</el-button>
    <div>
      <p v-if="isShow" class="text-danger">{{ msg }}</p>
    </div>
  </div>
</template>

<style scoped>
  .login{
    margin: 50px auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .login div{
    margin-top: 1rem;
  }

  .login label{
    display: inline-block;
    width: 50px;
    text-align-last: justify;
    padding: 0 10px;
  }

    button{
    margin-top: 25px;
  }

  .text-danger{
    color: red;
  }
</style>
